package com.qf.fmall.index.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall.index.entity.Category;
import com.qf.fmall.index.entity.Product;
import com.qf.fmall.index.entity.ProductImg;
import com.qf.fmall.index.mapper.CategoryDao;
import com.qf.fmall.index.mapper.ProductDao;
import com.qf.fmall.index.mapper.ProductImgDao;
import com.qf.fmall.index.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author leon
 * @since 2024-01-17
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category> implements ICategoryService {

    @Autowired
    private ProductDao productDao;

    @Autowired
    private ProductImgDao productImgDao;
    @Override
    public List<Category> categoryList() {


         //1.先查询所有一级分类信息
        List<Category> firstData = list(new QueryWrapper<Category>().eq("parent_id", 0));

        for (Category firstCategory : firstData) {



        //2.查询 一级下的 二级分类
        // 查询 id为1 的类的直属下级分类
        //select * from category where parent_id = 2
        Integer firstId = firstCategory.getCategoryId();
        List<Category>secondData = list(new QueryWrapper<Category>().eq("parent_id", firstId));
        //把查到的下级分类信息  设置到一级分类中
            firstCategory.setCategories(secondData);

            //遍历所有二级分类  查询三级分类
            for (Category secondCategory : secondData){
                Integer secondId = secondCategory.getCategoryId();
                List<Category> thirData = list(new QueryWrapper<Category>().eq("parent_id", secondId));
                secondCategory.setCategories(thirData);
            }

        }
        return firstData;
    }

    @Override
    public List<Category> categoryRecommends() {

        //1.查询所有一级分类
        List<Category> categories = list(new QueryWrapper<Category>().eq("parent_id", 0));


        //2.遍历一级分类，查询分类下的商品信息
        for (Category category : categories) {
            QueryWrapper<Product> queryWrapper = new QueryWrapper<>();


            queryWrapper.eq("root_category_id",category.getCategoryId());
            queryWrapper.orderByDesc("sold_num");
            queryWrapper.last("limit 6");
            List<Product> products = productDao.selectList(queryWrapper);

            if(products != null){

                addImgs(products);
                category.setProducts(products);
            }


        }



        return categories;
    }

    private void addImgs(List<Product> products) {
        //1.遍历每个商品查询对应的图片片信息
        for (Product product : products) {
            Integer productId = product.getProductId();
            List<ProductImg> imgs = productImgDao.selectList(new QueryWrapper<ProductImg>().eq("product_id", productId));
            product.setImgs(imgs);
        }
    }

}
